package com.leyou.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.domian.Sku;
import com.leyou.domian.Spu;
import com.leyou.domian.SpuDetail;
import com.leyou.dto.*;
import com.leyou.exception.LyException;
import com.leyou.exception.domain.ExceptionEnum;
import com.leyou.mapper.SkuMapper;
import com.leyou.mapper.SpuDetailMapper;
import com.leyou.mapper.SpuMapper;
import com.leyou.utils.BeanHelper;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class GoodsService {
    @Autowired
    SpuMapper spuMapper;
    @Autowired
    SkuMapper skuMapper;
    @Autowired
    SpuDetailMapper spuDetailMapper;

    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;

    public PageResult<SpuDTO> findGoodsPage(Integer pages, Integer rows, String key, Boolean saleable) {
        PageHelper.startPage(pages, rows);
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        if (!StringUtils.isBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        //封装是否上下架
        //数据库中的tinyint字段就是一个布尔类型，如果java传true则自动转成1，如果传false则自动转0
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }

        List<Spu> spus = spuMapper.selectByExample(example);
        //判空
        if (CollectionUtils.isEmpty(spus)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        PageInfo<Spu> pageInfo = new PageInfo<>(spus);
        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(spus, SpuDTO.class);
        handlerCategoryNameAndBrandName(spuDTOList);
        PageResult<SpuDTO> pageResult = new PageResult<>(spuDTOList, pageInfo.getSize(), pageInfo.getPageSize());
        return pageResult;

    }

    private void handlerCategoryNameAndBrandName(List<SpuDTO> spuDTOList) {
        spuDTOList.forEach(spuDTO -> {
            //先得到三个分类的名称拼接
            String categoryNames = categoryService.findCategoryByIds(spuDTO.getCategoryIds())//得到分类对象的集合
                    .stream()//得到集合流
                    .map(CategoryDto::getName)//收集每个对象中的name值
                    .collect(Collectors.joining("|"));//将收集到的name值以|分割，得到一个字符串
            spuDTO.setCategoryName(categoryNames);

            //得到品牌的名称
            String brandName = brandService.findBrandById(spuDTO.getBrandId()).getName();
            spuDTO.setBrandName(brandName);
        });

    }

    public void saveGoods(SpuDTO spuDTO) {
        //插入三张表
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        if (spu == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        spu.setSaleable(false);
        spuMapper.insertSelective(spu);
        Long spuId = spu.getId();

        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        spuDetail.setSpuId(spuId);
        spuDetailMapper.insertSelective(spuDetail);

        List<SkuDTO> skuDTOS = spuDTO.getSkus();

        List<Sku> skus = BeanHelper.copyWithCollection(skuDTOS, Sku.class);
        if (skus == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        skus.forEach(sku -> {
            sku.setSpuId(spuId);
            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
        });
        skuMapper.insertList(skus);
    }


    public void updateSaleable(Long id, Boolean saleable) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count < 1) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
    }

    public SpuDetailDTO findSpuDetail(Long id) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(id);
        SpuDetailDTO spuDetailDTO = BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
        if (spuDetailDTO == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return spuDetailDTO;
    }

    public List<SkuDTO> findSKus(Long id) {
        try {
            Sku sku = new Sku();
            sku.setSpuId(id);
            List<Sku> skuList = skuMapper.select(sku);
            List<SkuDTO> skuDTOS = BeanHelper.copyWithCollection(skuList, SkuDTO.class);
            if (CollectionUtils.isEmpty(skuDTOS)) {
                throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
            }
            return skuDTOS;
        }catch (Exception e){
            e.printStackTrace();
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
    }

    public void updateGoods(SpuDTO spuDTO) {

        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        if (spu == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        spu.setSaleable(false);
        spuMapper.updateByPrimaryKeySelective(spu);
        Long spuId = spu.getId();

        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        spuDetail.setSpuId(spuId);
        spuDetailMapper.updateByPrimaryKeySelective(spuDetail);

        //删除原来Spu下所有的Sku
        Sku record = new Sku();
        record.setSpuId(spuDTO.getId());
        skuMapper.delete(record);
        List<SkuDTO> skuDTOS = spuDTO.getSkus();

        List<Sku> skus = BeanHelper.copyWithCollection(skuDTOS, Sku.class);
        if (skus == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        skus.forEach(sku -> {
            sku.setSpuId(spuId);
            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
        });
        skuMapper.insertList(skus);
    }
}
